<template>
  <a-card class="tree-card">
    <TreeTools :tree-node="company" is-root @add-depart="addDeparts" />
    <!-- 树形组件 -->
    <a-tree
      v-if="treeData.length"
      default-expand-all
      block-node
      :tree-data="treeData"
      :field-names="fieldNames"
    >
      <template #title="data">
        <TreeTools
          :tree-node="data"
          @del-depts="getDeparts()"
          @add-depart="addDeparts"
          @edit-depart="editDeparts"
        />
      </template>
    </a-tree>
  </a-card>
  <AddDept
    ref="addDept"
    v-model:show-dialog="showDialog"
    :tree-node="treeNode"
    @refresh-list="getDeparts()"
  />
</template>

<script setup>
import { onMounted, ref } from 'vue'
import { transListToTreeData } from '@/utils'
import { getDepartment } from '@/api/department'
import TreeTools from './components/tree-tools.vue'
import AddDept from './components/add-dept.vue'

const fieldNames = {
  title: 'name',
  key: 'id'
}

const company = { name: '江苏传智播客教育科技股份有限公司', manager: '负责人', id: '' }

const treeData = ref([]) // 声明初始化数据

onMounted(() => {
  getDeparts()
})

const getDeparts = async () => {
  const { depts } = await getDepartment()
  treeData.value = transListToTreeData(depts, '')
}

const showDialog = ref(false)

// 添加部门
const treeNode = ref(null)
const addDeparts = (node) => {
  // 显示弹窗
  showDialog.value = true
  // 存储数据
  treeNode.value = node
}

// 编辑部门
const addDept = ref(null)
const editDeparts = async (node) => {
  // 调用子组件的方法
  await addDept.value.getDepartDetailFn(node.id)
  // 显示弹窗
  showDialog.value = true
  // 存储数据
  treeNode.value = node
}
</script>

<style scoped>
.tree-card {
  margin: 20px;
}
</style>
